<template>
  <div class="dialog-container">
    <div class="dialog-content">
      <el-form ref="form" :rules="rules" size="mini" :model="form" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item prop="label_id" label="所属标签">
              <el-select v-model="form.label_id" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="name" label="标签值">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="method" label="打标方式" required>
              <el-radio-group v-model="form.method">
                <el-radio disabled :label="1">手动打标</el-radio>
                <el-radio :label="2">自动打标(系统将在每日0点给已满足条件的用户打上标签)</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="rules" label="打标规则"></el-form-item>
        <div class="panel-line flex-end" style="margin-top: -20px">
          <el-button type="text" @click="handleAddData">+添加条件</el-button>
          <el-button type="text" @click="handleAddGroup">+添加条件组</el-button>
        </div>
        <div class="label-container">
          <el-select size="mini" class="option-type-select" v-model="form.option_type" placeholder="">
            <el-option v-for="item in optionTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <div class="label-list">
            <div class="label-item" v-for="(item, index) in form.rules" :key="item.id">
              <div class="label-group label-container" v-if="item.group_type === 'group'">
                <i class="el-icon-error" @click="handleRemoveGroup(index)"> </i>
                <el-select size="mini" class="option-type-select" v-model="item.option_type" placeholder="">
                  <el-option v-for="item in optionTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
                <div class="label-list">
                  <div class="label-item" v-for="(item1, index1) in item.option_list" :key="item1.id">
                    <OptionFormItem ref="OptionFormItem" v-if="baseSelect" :baseSelect="baseSelect" v-model="item1.content" @add="handleAddItem(index, index1)" @remove="handleRemoveItem(index, index1)"></OptionFormItem>
                  </div>
                </div>
              </div>
              <div class="label-single" v-else>
                <OptionFormItem ref="OptionFormItem" v-if="baseSelect" :baseSelect="baseSelect" v-model="item.option_list[0].content" @add="handleAddItem(index)" @remove="handleRemoveItem(index)"></OptionFormItem>
              </div>
            </div>
          </div>
        </div>
        <el-form-item style="margin-bottom: 0; margin-top: 40px">
          <div class="panel-line flex-end">
            <el-button @click="onCancel">取消</el-button>
            <el-button :loading="loading" type="primary" @click="onSubmit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { apiLabelValueDetail, apiLabelValueSave } from '@/api/dataStatistics'
import OptionFormItem from './OptionFormItem'

function getId() {
  return new Date().getTime() + '' + Math.floor(Math.random() * 100)
}

export default {
  name: 'DialogAdd',
  props: {
    labelList: {
      type: Array,
      default: () => {
        return []
      },
    },
    id: {
      type: String,
      default: '',
    },
    labelId: {
      type: String,
      default: '',
    },
  },
  components: { OptionFormItem },
  data() {
    let validaRules = (rule, value, callback) => {
      let result = true
      this.$refs.OptionFormItem.forEach((item) => {
        if (!item.validate()) {
          result = false
        }
      })
      if (!result) {
        callback(new Error('请将规则填写完整'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      baseSelect: null,
      editModel: 'add',
      detail: {},
      optionTypeList: [
        { value: 'and', label: '且' },
        { value: 'or', label: '或' },
      ],
      form: {
        label_id: '',
        name: '',
        method: 2,
        option_type: 'and',
        rules: [
          {
            id: getId(),
            group_type: 'single',
            option_type: 'and',
            option_list: [{ id: getId(), content: {} }],
          },
          {
            id: getId(),
            group_type: 'single',
            option_type: 'and',
            option_list: [{ id: getId(), content: {} }],
          },
        ],
      },
      rules: {
        label_id: [{ required: true, message: '请选择所属标签', trigger: 'blur' }],
        name: [{ required: true, message: '请输入标签值', trigger: 'blur' }],
        method: [{ required: true, message: '请选择打标方式', trigger: 'blur' }],
        rules: [
          { validator: validaRules, trigger: 'blur' },
          { required: true, message: '请设置打标规则', trigger: 'blur' },
        ],
      },
    }
  },
  mounted() {
    this.getSelect()
    this.init()
  },
  destroyed() {},
  methods: {
    // 获取下拉
    getSelect() {
      this.$store.dispatch('select/getLabelBaseInfo').then((res) => {
        this.baseSelect = res
      })
    },
    init() {
      if (this.id) {
        this.editModel = 'edit'
        this.getDetail()
      } else {
        this.editModel = 'add'
        if (this.labelId) {
          this.form.label_id = this.labelId
        }
      }
    },
    getDetail() {
      apiLabelValueDetail({ id: this.id }).then((res) => {
        this.detail = res.data
        this.setDetail()
      })
    },
    setDetail() {
      this.form.id = this.id
      this.form.label_id = this.detail.label_id
      this.form.name = this.detail.name
      this.form.method = this.detail.method
      this.form.option_type = this.detail.option_type
      this.form.rules = this.detail.rules.map((item) => {
        let newItem = {
          id: getId(),
          group_type: item.length > 1 ? 'group' : 'single',
          option_type: item[0].group_type,
          option_list: item.map((item2) => {
            return {
              id: getId(),
              content: {
                field: item2.id,
                option: item2.option,
                value: item2.value,
              },
            }
          }),
        }
        return newItem
      })
    },
    // 取消
    onCancel() {
      this.$emit('close')
    },
    formatSubmitData() {
      let formatData = {}
      if (this.editModel === 'edit') {
        formatData.id = this.form.id
      }
      formatData.label_id = this.form.label_id
      formatData.name = this.form.name
      formatData.method = this.form.method
      formatData.option_type = this.form.option_type
      formatData.rules = JSON.stringify(
        this.form.rules.map((item) => {
          let newItem = item.option_list.map((item2) => {
            return {
              id: item2.content.field,
              group_type: item.option_type,
              option: item2.content.option,
              value: item2.content.value,
            }
          })
          return newItem
        })
      )
      return formatData
    },
    // 保存
    onSubmit() {
      console.log(this.form)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          apiLabelValueSave(this.formatSubmitData())
            .then((res) => {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              setTimeout(() => {
                this.loading = false
                this.$emit('success')
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    handleAddData() {
      this.form.rules.push({
        id: getId(),
        group_type: 'single',
        option_type: 'and',
        option_list: [{ id: getId(), content: {} }],
      })
    },
    handleAddGroup() {
      this.form.rules.push({
        id: getId(),
        group_type: 'group',
        option_type: 'and',
        option_list: [
          { id: getId(), content: {} },
          { id: getId(), content: {} },
        ],
      })
    },
    handleAddItem(index, index1) {
      if (index1 !== undefined) {
        this.form.rules[index].option_list.splice(index1 + 1, 0, {
          id: getId(),
          content: {},
        })
      } else {
        this.form.rules.splice(index + 1, 0, {
          id: getId(),
          option_type: 'and',
          option_list: [{ id: getId(), content: {} }],
        })
      }
    },
    handleRemoveItem(index, index1) {
      if (index1 !== undefined) {
        this.form.rules[index].option_list.splice(index1, 1)
        if (this.form.rules[index].option_list.length === 0) {
          this.handleRemoveGroup(index)
        }
      } else {
        this.form.rules.splice(index, 1)
      }
    },
    handleRemoveGroup(index) {
      this.form.rules.splice(index, 1)
    },
  },
}
</script>

<style scoped lang="scss">
.label-container {
  background-color: #fcfcfc;
  border-radius: 4px;
  border: 1px solid #f1f2f4;
  padding: 24px 16px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.option-type-select {
  width: 60px;
  margin-right: 10px;
  position: relative;
  z-index: 2;
}
.label-list {
  flex-grow: 1;
  .label-item {
    position: relative;
    padding: 6px 0;
    &:before {
      content: '';
      width: 15px;
      height: 100%;
      border-left: 1px solid #afafa0;
      position: absolute;
      left: -40px;
      top: 0;
    }
    &:first-child::before {
      height: 50%;
      border-top: 1px solid #afafa0;
      border-top-left-radius: 6px;
      top: 50%;
    }
    &:last-child::before {
      height: 50%;
      border-bottom: 1px solid #afafa0;
      border-bottom-left-radius: 6px;
    }
    &:only-child::before {
      border: none;
    }
  }
}
.label-group {
  border: 1px dashed #ccc;
  border-radius: 4px;
  padding: 16px 12px;
  position: relative;
  .el-icon-error {
    position: absolute;
    top: -14px;
    right: -9px;
    font-size: 18px;
    color: #a5a4a4;
    line-height: 28px;
    margin-left: 6px;
    cursor: pointer;
    &:hover {
      color: #f56c6c;
    }
  }
}
::v-deep .el-input__inner {
  border-color: #afafa0;
}
</style>
